from dvadmin.utils.json_response import SuccessResponse, DetailResponse
from rest_framework.decorators import action
import pandas as pd

from dvadmin.utils.viewset import CustomModelViewSet

from se_admin.tables.SrvTables.serializers import HardwareClassSerializer, ServiceClassSerializer, ServerSerializer
from se_admin.tables.SrvTables.serializers import SrvAccountSerializer, SrvAccountImportSerializer, SrvAccountExportSerializer, SrvAccountCreateUpdateSerializer
from se_admin.tables.SrvTables.serializers import PhyServerSerializer, PhyServerCreateUpdateSerializer, PhyServerImportSerializer, PhyServerExportSerializer
from se_admin.tables.SrvTables.serializers import VmServerSerializer, VmServerCreateUpdateSerializer, VmServerImportSerializer, VmServerExportSerializer
from se_admin.tables.SrvTables.filters import ServerStatusFilter, SrvAccountFilter


# 资产类型字典
class HardwareClassViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = HardwareClassSerializer.Meta.model.objects.all()
    serializer_class = HardwareClassSerializer

# 资产状态字典
class ServiceClassViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = ServiceClassSerializer.Meta.model.objects.all()
    serializer_class = ServiceClassSerializer

class ServerViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = ServerSerializer.Meta.model.objects.all()
    serializer_class = ServerSerializer

    # 注释编号:django-vue3-admin_views211216
    # 功能说明:被访问的model他要拿到外健的外键的值而进行重写懒加载请求，专门返回该字段外健的外键的值
    
    @action(methods=['post'], detail=False)
    def getbyIds(self, request, *args, **kwargs):
        try:
            idList = request.data['values'] #获取前端传过来
        except:
             return DetailResponse(data=queryset, msg="没有传values到后端, 即是id列表")

        cur_model = self.get_queryset().model  #查到当前的model

        queryset_id = cur_model.objects.filter(id__in=idList)  #过滤出来前端传过来的list列表里面的对象
        queryset = list(queryset_id.values())

        try:
            fieldList = request.data['fieldList']

            df = pd.DataFrame(queryset, columns=fieldList)  #转换为pandas DataFrame格式，并且只拿其中列表内规定的字段

            newField =  fieldList[1].replace('_id', '') #把拿到的列表如['id', 'it_use_id']中的第二个元素fieldList[1]=it_use_id拿出来进行去除__id后缀

            try:
                #这里是拿到当前cur_model对应的newKey的外健对象的所有值并转为这字典
                choices_dict = dict(getattr(cur_model, newField).field.get_choices())
                #然后把对应的外健的值给组装回去df内
                df[f'{fieldList[1]}'] =  df[f'{fieldList[1]}'].replace(choices_dict)
            except AttributeError:
                #即是出现AttributeError: 'NoneType' object has no attribute 'model'错误时,不用理会
                pass
            queryset = df.to_dict(orient='records')  #pandas DataFrame转换成包含字典的列表格式

        except:
            pass

        return DetailResponse(data=queryset, msg="获取成功")
    # 注释编号:django-vue3-admin_views211216

class SrvAccountViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = SrvAccountSerializer.Meta.model.objects.all()
    serializer_class = SrvAccountSerializer
    create_serializer_class = SrvAccountCreateUpdateSerializer
    update_serializer_class = SrvAccountCreateUpdateSerializer
    
    filter_class = SrvAccountFilter

    export_field_label = {
        "server": "服务器",
        "server_ip": "服务器IP",
        "account": "账号",
        "current_passwd": "当前密码",
        "passwd_expire": "密码过期时间",
        "last_passwd": "上次密码",
        "last_change": "上次改密时间",
        "next_passwd": "下次改密",
        "next_change": "下次改密时间",
        "is_change": "是否改密",
        "remark": "备注",
        "update_datetime": "更新时间",
    }
    export_serializer_class = SrvAccountExportSerializer

    import_field_dict = {
        "server": "服务器",
        "account": "账号",
        "current_passwd": "当前密码",
        "passwd_expire": "密码过期时间",
        "last_passwd": "上次密码",
        "last_change": "上次改密时间",
        "next_passwd": "下次改密",
        "next_change": "下次改密时间",
        "is_change": "是否改密",
        "remark": "备注",
    }
    import_serializer_class = SrvAccountImportSerializer


class PhyServerViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = PhyServerSerializer.Meta.model.objects.filter(is_vm=False)
    serializer_class = PhyServerSerializer
    filter_class = ServerStatusFilter
    create_serializer_class = PhyServerCreateUpdateSerializer
    update_serializer_class = PhyServerCreateUpdateSerializer

    export_field_label = {
        'name': '服务器名',
        'astag': '资产编号',
        'hw_class': '硬件类别',
        'manufacturer': '厂商',
        'model': '型号',
        'sn': '序列号',
        'serverroom': '机房',
        'rack': '机柜',
        'rack_unit': '机架位',
        'spec_disk': '硬盘规格',
        'spec_special': '特殊配置',
        'bmc_ip': 'BMC IP',
        'bmc_version': 'BMC版本',
        'bmc_account': 'BMC账号',
        'bmc_passwd': 'BMC密码',
        'service_class': '服务类型',
        'hostname': '主机名',
        'ipaddress': 'IP地址',
        'domain': '域名',
        'os_type': 'OS类别',
        'os_version': 'OS版本',
        'backup_ip': '备份IP',
        'sub_ipaddress': '子IP地址',
        'cpu_model': 'CPU型号',
        'cpu_socket': 'CPU颗数',
        'cpu_cores': '总核数',
        'men_num': '内存条数',
        'mem_size': '内存容量',
        'disk_size': '硬盘容量',
        'owner_func': '归属部门',
        'owner': '管理员',
        'owner_leader': '管理主管',
        'form_online': '上架单号',
        'form_offline': '下架单号',
        # 'superuser': '管理账号',
        # 'superpasswd': '管理密码',
        'remark': '备注',
        'update_datetime': '更新时间',
    }
    export_serializer_class = PhyServerExportSerializer

    import_field_dict = {
        'name': '服务器名',
        'astag': '资产编号',
        'hw_class': '硬件类别',
        'manufacturer': '厂商',
        'model': '型号',
        'sn': '序列号',
        'serverroom': '机房',
        'rack': '机柜',
        'rack_unit': '机架位',
        'spec_disk': '硬盘规格',
        'spec_special': '特殊配置',
        'bmc_ip': 'BMC IP',
        'bmc_version': 'BMC版本',
        'bmc_account': 'BMC账号',
        'bmc_passwd': 'BMC密码',
        'service_class': '服务类型',
        'hostname': '主机名',
        'ipaddress': 'IP地址',
        'domain': '域名',
        'os_type': 'OS类别',
        'os_version': 'OS版本',
        'backup_ip': '备份IP',
        'sub_ipaddress': '子IP地址',
        'cpu_model': 'CPU型号',
        'cpu_socket': 'CPU颗数',
        'cpu_cores': '总核数',
        'men_num': '内存条数',
        'mem_size': '内存容量',
        'disk_size': '硬盘容量',
        'owner_func': '归属部门',
        'owner': '管理员',
        'owner_leader': '管理主管',
        'form_online': '上架单号',
        'form_offline': '下架单号',
        # 'superuser': '管理账号',
        # 'superpasswd': '管理密码',
        'remark': '备注',
    }
    import_serializer_class = PhyServerImportSerializer


class VmServerViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = VmServerSerializer.Meta.model.objects.filter(is_vm=True)
    serializer_class = VmServerSerializer
    filter_class = ServerStatusFilter
    create_serializer_class = VmServerCreateUpdateSerializer
    update_serializer_class = VmServerCreateUpdateSerializer

    import_field_dict = {
        'vmid': 'VM编号', 
        'name': 'VM名称',
        'vmtool': 'Tool状态',
        'service_class': '服务类型',
        'hostname': '主机名',
        'domain': '域名',
        'ipaddress': 'IP地址',
        'nics': '网卡数量',
        'os_type': 'OS类别',
        'os_version': 'OS版本',
        'backup_ip': '备份IP',
        'sub_ipaddress': '子IP地址',
        'cpu_cores': '总核数',
        'mem_size': '内存容量',
        'disk_num': '硬盘数量',
        'disk_size': '硬盘容量',
        'vmhost': '宿主机',
        'vmdatastore': '数据存储',
        #'is_vm': '是否虚拟机',
        'owner_func': '归属部门',
        'owner': '管理员',
        'owner_leader': '管理主管',
        'form_online': '上架单号',
        'form_offline': '下架单号',
        'remark': '备注',
    }
    import_serializer_class = VmServerImportSerializer

    export_field_label = {
        'vmid': 'VM编号', 
        'name': 'VM名称',
        'vmtool': 'Tool状态',
        'service_class': '服务类型',
        'hostname': '主机名',
        'domain': '域名',
        'ipaddress': 'IP地址',
        'nics': '网卡数量',
        'os_type': 'OS类别',
        'os_version': 'OS版本',
        'backup_ip': '备份IP',
        'sub_ipaddress': '子IP地址',
        'cpu_cores': '总核数',
        'mem_size': '内存容量',
        'disk_num': '硬盘数量',
        'disk_size': '硬盘容量',
        'vmhost': '宿主机',
        'vmdatastore': '数据存储',
        #'is_vm': '是否虚拟机',
        'owner_func': '归属部门',
        'owner': '管理员',
        'owner_leader': '管理主管',
        'form_online': '上架单号',
        'form_offline': '下架单号',
        'remark': '备注',
        'update_datetime': '更新时间',
    }
    export_serializer_class = VmServerExportSerializer
       






